﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Win32;
using System.Security.Cryptography;

namespace Crm.Utilities.SolutionsDeploymentTool.UI.Helpers
{
    public static class Encryption
    {
        private static readonly byte[] TRIPLE_DES_KEY = {229, 20, 150, 220, 180, 60, 230, 30,
                                                 160, 158, 199, 45, 76, 31, 73, 240, 
                                                 51, 17, 142, 46, 109, 22, 90, 89};
        private static readonly byte[] TRIPLE_DES_IV = { 229, 202, 22, 243, 14, 105, 229, 252, 25, 89, 169 };

        public static string TripleDESEncrypt(string value)
        {
            TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream();
            Byte[] key = TRIPLE_DES_KEY;
            Byte[] IV = TRIPLE_DES_IV;

            CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateEncryptor(key, IV), CryptoStreamMode.Write);
            StreamWriter sw = new StreamWriter(cs);

            sw.Write(value);
            sw.Flush();
            cs.FlushFinalBlock();
            ms.Flush();

            //convert back to a string
            return Convert.ToBase64String(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length)); ;
        }

        public static string TripleDESDecrypt(string value)
        {
            TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider();
            Byte[] KEY_64 = TRIPLE_DES_KEY;
            Byte[] IV_64 = TRIPLE_DES_IV;

            Byte[] buffer = Convert.FromBase64String(value);
            MemoryStream ms = new MemoryStream(buffer);
            CryptoStream cs = new CryptoStream(ms, cryptoProvider.CreateDecryptor(KEY_64, IV_64), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cs);

            return sr.ReadToEnd();

        }

    }
}
